/*
 * SaleReturn.java
 *
 * Created on April 1, 2007, 11:23 AM
 */

package edu.byu.isys413.jjenkins.view;

import edu.byu.isys413.jjenkins.data.CustomerBO;
import edu.byu.isys413.jjenkins.data.DataException;
import edu.byu.isys413.jjenkins.data.TransactionBO;
import edu.byu.isys413.jjenkins.data.TransactionDAO;
import java.sql.SQLException;
import java.text.NumberFormat;
import java.util.List;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import java.sql.Date;

/**
 * This form processes the sale return transaction, it is called form the NewOrder Form
 * @author Rick
 */
public class SaleReturn extends javax.swing.JFrame {
    
    DefaultListModel model = new DefaultListModel();
    List<TransactionBO> li;
    CustomerBO cust;
    private static SaleReturn instance = null;
    
    
    /**
     * ensures that it only gets the single instance
     * @return instance
     */
    public static synchronized SaleReturn getInstance() {
        
        if (instance == null) {
            instance = new SaleReturn();
        }
        
        
        return instance;
    }
    
    /** Creates new form SaleReturn */
    public SaleReturn() {
        initComponents();
        tlist.setModel(model);
        this.setLocationRelativeTo(null);
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        custName = new javax.swing.JTextField();
        criteria = new javax.swing.JTextField();
        searchByTransId = new javax.swing.JButton();
        next = new javax.swing.JButton();
        cancel = new javax.swing.JButton();
        transList = new javax.swing.JScrollPane();
        tlist = new javax.swing.JList();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Select Transaction to Return");
        jLabel1.setText("Transactions for:");

        searchByTransId.setText("Search by Transaction ID");
        searchByTransId.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                searchByTransIdActionPerformed(evt);
            }
        });

        next.setText("Next");
        next.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nextActionPerformed(evt);
            }
        });

        cancel.setText("Cancel");
        cancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelActionPerformed(evt);
            }
        });

        tlist.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        transList.setViewportView(tlist);

        jLabel2.setText("If transaction is not found for this customer, enter the transaction id");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(custName, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel2)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addComponent(transList, javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                            .addComponent(criteria, javax.swing.GroupLayout.PREFERRED_SIZE, 174, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(searchByTransId))
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addComponent(cancel)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(next))))
                .addContainerGap(71, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(custName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addGap(4, 4, 4)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(criteria, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(searchByTransId))
                .addGap(54, 54, 54)
                .addComponent(transList, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 33, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(next)
                    .addComponent(cancel)))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void nextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nextActionPerformed
// TODO add your handling code here:
        System.out.println(tlist.getSelectedIndex());
        SaleReturn2.getInstance().loadForm(li.get(tlist.getSelectedIndex()),cust);
    }//GEN-LAST:event_nextActionPerformed
    
    private void searchByTransIdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_searchByTransIdActionPerformed
// TODO add your handling code here:
        try {
            String transid = criteria.getText();
            TransactionBO trans;
            
            trans = TransactionDAO.getInstance().read(transid);
            
            CustomerBO cust = trans.getCustomer();
            SaleReturn2.getInstance().loadForm(trans, cust);
        } catch (DataException ex) {
            ex.printStackTrace();
        }
    }//GEN-LAST:event_searchByTransIdActionPerformed
    
    private void cancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelActionPerformed
// TODO add your handling code here:
        this.dispose();
    }//GEN-LAST:event_cancelActionPerformed
    
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new SaleReturn().setVisible(true);
            }
        });
    }
    
    /**
     * loads the information passsed in
     * @param cust 
     */
    public void loadForm(CustomerBO cust) {
        
            
            custName.setText(cust.getFirstName()+" "+cust.getLastName());
            this.cust = cust;
            System.out.println("cust id is "+cust.getId());
            //List tlist = TransactionDAO.getInstance().readByCustomer(cust.getId());
            //now how to add each line to the jlist?
            
            //they click on a transaction, then click next
            //code will be something like
            //SaleReturn2.getInstance.loadForm(jlist.getSelectedIndex)
            //SaleReturn2.getInstance().loadForm("t3", cust);
            //or something like this, basically it will pass in the transactionid of the transaction to display
            
            
        populateTransactions();
        this.setVisible(true);
    }
    
    
    /**
     * populates the information that was send in
     */
     public void populateTransactions(){
        try{
            NumberFormat currency = NumberFormat.getCurrencyInstance();
//            trans.endTransaction();
//            lblSubTotal.setText(currency.format(trans.getSubtotal()));
//            lblTax.setText(currency.format(trans.getTax()));
//            lblTotal.setText(currency.format(trans.getTotal()));
            model.removeAllElements();
            
            
            // List of all interesets
//            li =  trans.getTransactionList();
            li = TransactionDAO.getInstance().readByCustomer(cust.getId());
            
            
            // creaetes entries
            for(int i = 0; i < li.size(); i++){
                
                TransactionBO line =li.get(i);
                System.out.println("inside for loop in populate lines for "+line.getId());
                Date date;
                double total = 0.00;
                String type = "-";
                
                //checks to see if there is a revenue source
                date = line.getDate();
                total = line.getTotal();
                type = line.getType();
               
                //quan = line.getRevenueSource().getQuantity() + "";
                //double price = line.getSubtotal();
                
                
                // This add space onto the description to have uniform formatting
//                while(description.length()<35){
//                    description += " ";
//                }
                
                //checks to see if there is a coupon

                String strLine  =date + "           type:  "+ type+"           total:  " + currency.format(total);
                
                model.addElement(strLine);
                
                this.setVisible(true);
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null,ex.toString(),"No transactions found for this customer", JOptionPane.ERROR_MESSAGE);
        } catch (DataException ex) {
            ex.printStackTrace();
        }
        
        
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancel;
    private javax.swing.JTextField criteria;
    private javax.swing.JTextField custName;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JButton next;
    private javax.swing.JButton searchByTransId;
    private javax.swing.JList tlist;
    private javax.swing.JScrollPane transList;
    // End of variables declaration//GEN-END:variables
    
}
